import { putch } from '@/utils/request'
import { Form, Input, Button, FormInstance } from '@arco-design/web-react'
import { forwardRef, useEffect, useImperativeHandle } from 'react'
const FormItem = Form.Item

type ChildProps = {
  data: {
    [key in string]: any
  }
  //   onSubmit: (values: any) => void
}
export type ChildRef = Pick<FormInstance<any>, 'clearFields' | 'setFieldsValue'> & {
  handleSubmit: () => void
}
const MonitorForm = forwardRef<ChildRef, ChildProps>((props, ref) => {
  const [form] = Form.useForm()
  const { data } = props
  const handleSubmit = () => {
    return new Promise((resolve, reject) => {
      form
        .validate()
        .then(async (values) => {
          await putch('/api/v1/user/' + data.id, { profile: values })
          resolve(values)
        })
        .catch(() => {
          reject()
        })
    })
  }
  // const clearFields = form.clearFields
  useImperativeHandle(
    ref,
    () => ({
      handleSubmit,
      clearFields: form.clearFields,
      setFieldsValue: form.setFieldsValue
    }),
    []
  )
  useEffect(() => {
    form.setFieldsValue(data)
  }, [data])
  return (
    <Form form={form} autoComplete="off">
      <FormItem label="姓名" field="name">
        <Input placeholder="please enter your name" />
      </FormItem>
      <FormItem label="年龄" field="age">
        <Input placeholder="please enter your age" type="number" />
      </FormItem>
      <FormItem label="邮件" field="email">
        <Input placeholder="please enter your email" />
      </FormItem>
      <FormItem label="电话" field="phone">
        <Input placeholder="please enter your phone" />
      </FormItem>
      <FormItem label="地址" field="address">
        <Input placeholder="please enter your address" />
      </FormItem>
      <FormItem wrapperCol={{ offset: 5 }}>
        <Button
          style={{ marginRight: 24 }}
          onClick={() => {
            form.resetFields()
          }}
        >
          重置
        </Button>
      </FormItem>
    </Form>
  )
})

export default MonitorForm
